package cn.kgc.rbac.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.kgc.rbac.common.CodeMsg;
import cn.kgc.rbac.common.ResponseResult;
import cn.kgc.rbac.dto.UserPageDTO;
import cn.kgc.rbac.entity.*;
import cn.kgc.rbac.mapper.*;
import cn.kgc.rbac.utils.SaltUtil;
import cn.kgc.rbac.utils.TreeUtil;
import cn.kgc.rbac.vo.PermissionVO;
import cn.kgc.rbac.vo.UserVO;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.kgc.rbac.service.UserService;
import com.mysql.jdbc.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 *
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService{

    @Autowired(required = false)
    private UserMapper userMapper;

    @Autowired(required = false)
    private UserRoleMapper  userRoleMapper;

    @Autowired(required = false)
    private RoleMapper roleMapper;

    @Autowired(required = false)
    private RolePersMapper rolePersMapper;

    @Autowired(required = false)
    private PermissionMapper permissionMapper;
    @Override
    public ResponseResult selectPage(UserPageDTO userPageDTO) {

        Page<User> userPage = new Page<>(userPageDTO.getPage(), userPageDTO.getLimit());

       /*
       * username  city
       * select  * from  user limit ?  查询所有
       * select  * from  user   where  username = username  limit ?  搜索条件 username
       * select  * from  user   where  city = city  limit ?  搜索条件 city
       * select  * from  user   where  city = city  and username = username   limit ?  搜索条件 city  name
       * */

        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();

        // 动态sql
        lambda.eq(!StringUtils.isNullOrEmpty(userPageDTO.getUsername()), User::getUsername,userPageDTO.getUsername())
                .eq(!StringUtils.isNullOrEmpty(userPageDTO.getCity()), User::getCity,userPageDTO.getCity());

        userMapper.selectPage(userPage,lambda);

        // 通过page  获取相关分页数据
        long total = userPage.getTotal();
        List<User> records = userPage.getRecords();
        // User - > UserVO 角色名称
        List<UserVO> collect = records.stream().map(user -> {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            // 获取用户id  查询角色信息
            Integer userId = user.getId();
            QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
            userRoleQueryWrapper.eq("user_id", userId);

            List<UserRole> userRoles = userRoleMapper.selectList(userRoleQueryWrapper);
            //遍历集合 获取角色id  user_role
            List<Integer> roleIds = userRoles.stream().map(userRole -> {
                return userRole.getRoleId();
            }).collect(Collectors.toList());

            // 根据角色id 查询角色信息  role
            QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
            roleQueryWrapper.in("role_id", roleIds);
            List<Role> roles = roleMapper.selectList(roleQueryWrapper);

            // 遍历角色集合 获取角色名字
            List<String> roleNames = roles.stream().map(role -> {
                return role.getComments();
            }).collect(Collectors.toList());

            userVO.setRoles(roleNames);
            return userVO;
        }).collect(Collectors.toList());

        return new ResponseResult(CodeMsg.SUCCESS,collect,total);
    }

    @Override
    public ResponseResult addUser(UserVO userVO) {

        // 判定用户名是否可用
        String username = userVO.getUsername();
        User usr = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if(ObjectUtil.isNotNull(usr)){
            return new ResponseResult(CodeMsg.USER_EXIST);
        }else {
            //  添加用户  user
            User user = new User();
            BeanUtils.copyProperties(userVO , user);
            //保存用户信息   设置用户的初始密码
            String salt = SaltUtil.getSalt(8);
            user.setSalt(salt);
            String md5PWD = new Md5Hash("888888", salt, 50).toHex();
            user.setPassword(md5PWD);

            userMapper.insert(user);
            // 添加用户角色信息  userId  roleId
            List<Integer> roleIds = userVO.getRoleIds();//[2,5]
            Integer userId = user.getId();   //20 2  20 5  user_role

            roleIds.forEach(roleId->{
                UserRole userRole = new UserRole();
                userRole.setRoleId(roleId);
                userRole.setUserId(userId);
                userRoleMapper.insert(userRole);
            });

            return new ResponseResult(CodeMsg.SUCCESS);
        }

    }

    @Override
    public ResponseResult getUserById(Integer id) {

        User user = userMapper.selectById(id);

        LambdaQueryWrapper<UserRole> lambda = new QueryWrapper<UserRole>().lambda();
        lambda.eq(UserRole::getUserId,id);
        List<UserRole> userRoles = userRoleMapper.selectList(lambda);

        List<Integer> roleIds = userRoles.stream().map(userRole -> {
            return userRole.getRoleId();
        }).collect(Collectors.toList());

        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setRoleIds(roleIds);

        return new ResponseResult(CodeMsg.SUCCESS,userVO , null);
    }

    @Override
    public ResponseResult updateUser(UserVO userVO) {

        //  user
        User user = new User();
        BeanUtils.copyProperties(userVO, user);
        userMapper.updateById(user);

        List<Integer> roleIds = userVO.getRoleIds();

        // 角色信息更新   1.根据用户的id删除用户的角色信息  2.根据用户新提交的角色id  insert
        Integer userId = user.getId();
        userRoleMapper.delete(new QueryWrapper<UserRole>().eq("user_id", userId));

        roleIds.forEach(roleId->{
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        });

        return new ResponseResult(CodeMsg.SUCCESS);
    }

    @Override
    public ResponseResult deleteByUserId(String ids) {

        String[] strIds = ids.split(",");
        ArrayList<Integer> integerIds = new ArrayList<>();
        for (String strId : strIds) {
            integerIds.add(Integer.valueOf(strId));
        }
        //删除用户信息
        userMapper.deleteBatchIds(integerIds);
        //删除用户角色信息
        QueryWrapper<UserRole> userRoleQueryWrapper = new QueryWrapper<>();
        userRoleQueryWrapper.in("user_id", integerIds);
        userRoleMapper.delete(userRoleQueryWrapper);

        return new ResponseResult(CodeMsg.SUCCESS);
    }

    @Override
    public Map<String, Object> loadMenu(String username) {
        /*
        * {
        *   "homeinfo":{},
        *   logoinfo:{},
        *   menuinfo:{}
        * }
        * */
        Map<String, Object> map = new HashMap<>(16);
        Map<String,Object> home = new HashMap<>(16);
        Map<String,Object> logo = new HashMap<>(16);

        //首页信息初始化     "title": "首页",
        //    "href": "https://www.8zt.cc"
        home.put("title","首页");
        home.put("href","https://www.8zt.cc");

        map.put("homeInfo",home);

        // logo信息初始化  "title": "LAYUI MINI",
        //    "image": "images/logo.png",
        //    "href": ""
        logo.put("title","KGC");
        logo.put("image","images/logo.png");
        logo.put("href","www.baidu.com");
        map.put("logoInfo", logo);

        // 根据用户名 查询用户的权限信息

        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        Integer userId = user.getId();

        //根据用户id  查询用户角色id
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", userId));
        List<Integer> roleIds = userRoles.stream().map(userRole -> {
            return userRole.getRoleId();
        }).collect(Collectors.toList());

        // 根据角色id  查询角色权限关联表
        List<RolePers> rolePers = rolePersMapper.selectList(new QueryWrapper<RolePers>().in("role_id", roleIds));
        List<Integer> collect = rolePers.stream().map(rp -> {
            return rp.getPerId();
        }).collect(Collectors.toList());

        //根据权限id查询权限详细信息
        List<Permission> permissions = permissionMapper.selectBatchIds(collect);

        List<PermissionVO> permissionVOs = permissions.stream().map(permission -> {
            PermissionVO permissionVO = new PermissionVO();
            BeanUtils.copyProperties(permission, permissionVO);
            return permissionVO;
        }).filter(p -> p.getIsMenu()!= 2).collect(Collectors.toList());

        System.out.println("permissionVOs = " + permissionVOs);

        // 实现权限的挂载 树形结构
        List<PermissionVO> ps = TreeUtil.toTree(permissionVOs, 0);
        // 设置菜单信息
        map.put("menuInfo",ps);
        return map;
    }
}




